﻿using Grow.Module.Builder;
using Grow.Utils.Exceptions;
using System.Collections.Concurrent;

namespace Grow.AspNetCore.Builder
{
    public class BuilderManager : IBuilderManager
    {
        private readonly ConcurrentDictionary<Type, object?> _builders;
        public BuilderManager()
        {
            _builders = new();
        }

        public TBuilder? GetBuilder<TBuilder>() where TBuilder : IBuilder
        {
            Type builderType = typeof(TBuilder);
            if (_builders.TryGetValue(builderType, out object? service))
            {
                if (service is TBuilder tBuilder)
                {
                    return tBuilder;
                }
            }
            return default;
        }

        public TBuilder GetRequiredBuilder<TBuilder>() where TBuilder : IBuilder
        {
            TBuilder? builder = GetBuilder<TBuilder>();
            return builder is not null ? builder : throw new GrowCheckException($"类型为“{typeof(TBuilder).FullName}”的 Builder无法找到");
        }

        public void SetBuilder<TBuilder>(TBuilder builder) where TBuilder : IBuilder
        {
            Type builderType = typeof(TBuilder);
            _ = _builders.AddOrUpdate(builderType, _ => builder, (_, _) => builder);
        }
    }
}
